package com.azxcrm.project.system.order.controller;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import org.activiti.engine.RuntimeService;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.azxcrm.common.utils.DateUtils;
import com.azxcrm.common.utils.RandomUtils;
import com.azxcrm.common.utils.StringUtils;
import com.azxcrm.common.utils.security.ShiroUtils;
import com.azxcrm.framework.aspectj.lang.annotation.Log;
import com.azxcrm.framework.redis.template.service.RedisServiceImpl;
import com.azxcrm.framework.web.controller.BaseController;
import com.azxcrm.framework.web.domain.Message;
import com.azxcrm.framework.web.page.TableDataInfo;
import com.azxcrm.project.monitor.workflow.common.CommonService;
import com.azxcrm.project.monitor.workflow.domain.WorkFlowApply;
import com.azxcrm.project.monitor.workflow.service.WorkFlowApplyService;
import com.azxcrm.project.system.basic.dao.IOrderDispatchDao;
import com.azxcrm.project.system.basic.domain.CustomerClueCommunication;
import com.azxcrm.project.system.basic.domain.OrderDispatch;
import com.azxcrm.project.system.basic.domain.OrderModifyRecord;
import com.azxcrm.project.system.basic.service.ICustomerClueCommunicationService;
import com.azxcrm.project.system.basic.service.IOrderDispatchService;
import com.azxcrm.project.system.basic.service.IOrderModifyRecordService;
import com.azxcrm.project.system.customer.domain.CustomerAttendance;
import com.azxcrm.project.system.customer.domain.CustomerClue;
import com.azxcrm.project.system.customer.domain.CustomerInfo;
import com.azxcrm.project.system.customer.service.ICustomerAttendanceService;
import com.azxcrm.project.system.customer.service.ICustomerClueService;
import com.azxcrm.project.system.customer.service.ICustomerInfoService;
import com.azxcrm.project.system.dept.domain.Dept;
import com.azxcrm.project.system.dept.service.IDeptService;
import com.azxcrm.project.system.dict.domain.DictData;
import com.azxcrm.project.system.dict.service.IDictDataService;
import com.azxcrm.project.system.order.domain.Order;
import com.azxcrm.project.system.order.domain.OrderAudit;
import com.azxcrm.project.system.order.domain.OrderDeal;
import com.azxcrm.project.system.order.domain.OrderVisitRecord;
import com.azxcrm.project.system.order.domain.OrdersSet;
import com.azxcrm.project.system.order.service.IOrderDealService;
import com.azxcrm.project.system.order.service.IOrderService;
import com.azxcrm.project.system.order.service.IOrderVisitRecordService;
import com.azxcrm.project.system.product.domain.ProductInfo;
import com.azxcrm.project.system.product.domain.ProductSpecification;
import com.azxcrm.project.system.product.service.IProductInfoService;
import com.azxcrm.project.system.product.service.IProductSpecificationService;
import com.azxcrm.project.system.user.domain.User;
import com.azxcrm.project.system.user.service.IUserService;

/**
 * 订单 控制层处理
 * 
 * @author Dustyone
 * @date 2018-09-11
 */
@Controller
@RequestMapping("/module/order")
public class OrderController extends BaseController {
	private String prefix = "module/order";

	/**
	 * 字典产品类型
	 */
	@Value("${crm.dictionary.product.type.orign}")
	private String productType;

	/**
	 * 拜访类型
	 */
	@Value("${crm.dictionary.visit.type}")
	private String visitType;

	/**
	 * 客户工作类型
	 */
	@Value("${crm.dictionary.customer.job}")
	private String job;

	/**
	 * 客户背景类型
	 */
	@Value("${crm.dictionary.customer.background}")
	private String customerBackground;

	/**
	 * 审批工作流之成单审批
	 */
	@Value("${crm.workflow.deal}")
	private String dealProcess;

	/**
	 * 审批工作流之退单审批
	 */
	@Value("${crm.workflow.refund}")
	private String refundProcess;

	/**
	 * 订单信息
	 */
	@Autowired
	private IOrderService orderService;

	/**
	 * 常见问题类型
	 */
	@Autowired
	private IDictDataService dictDataService;

	/**
	 * 客户信息
	 */
	@Autowired
	private ICustomerInfoService customerInfoService;

	/**
	 * 业务员信息
	 */
	@Autowired
	private IUserService userService;

	@Autowired
	private CommonService commonService;

	@Autowired
	private RuntimeService runtimeService;

	@Autowired
	private WorkFlowApplyService workFlowApplyService;

	@Autowired
	private IOrderDealService orderDealService;

	/**
	 * 回访记录表
	 */
	@Autowired
	private IOrderVisitRecordService orderVisitRecordService;

	/**
	 * 客户线索
	 */
	@Autowired
	private ICustomerClueService customerClueService;

	/**
	 * 参课信息
	 */
	@Autowired
	private ICustomerAttendanceService customerAttendanceService;

	/**
	 * 派单记录
	 */
	@Autowired
	private IOrderDispatchService orderDispatchService;

	@Autowired
	private IOrderDispatchDao orderDispatchDao;

	/**
	 * 部门信息
	 */
	@Autowired
	private IDeptService deptService;

	/**
	 * 订单操作记录
	 */
	@Autowired
	private IOrderModifyRecordService orderModifyRecordService;

	@Autowired
	private IProductInfoService productInfoService;

	@Autowired
	private IProductSpecificationService productSpecificationService;

	/**
	 * 客服沟通记录
	 */
	@Autowired
	private ICustomerClueCommunicationService customerClueCommunicationService;

	/**
	 * Redis服务
	 */
	@Autowired
	private RedisServiceImpl redisServiceImpl;

	/**
	 * 派单员角色
	 */
	@Value("${crm.role.dispatcher}")
	private String dispatcher;

	/**
	 * 派单员主管
	 */
	@Value("${crm.role.dispatcherManager}")
	private String dispatcherManager;

	/**
	 * 业务员角色
	 */
	@Value("${crm.role.salesman}")
	private String salesman;

	/**
	 * 客服
	 */
	@Value("${crm.role.customerService}")
	private String customerService;

	/**
	 * 财务
	 */
	@Value("${crm.role.treasurer}")
	private String treasurer;

	/**
	 * 管理员
	 */
	@Value("${crm.role.admin}")
	private String admin;

	@Log(title = "订单管理", action = "成单列表-成单列表信息")
	@GetMapping()
	@RequiresPermissions("module:order:view")
	String order() {
		return prefix + "/order";
	}

	/**
	 * 查询订单列表
	 */
	@Log(title = "订单管理", action = "成单列表-成单列表信息")
	@GetMapping("/list")
	@RequiresPermissions("module:order:list")
	@ResponseBody
	public TableDataInfo list(OrderDeal orderDeal, Model model) {
		setPageInfo(orderDeal);
		Order order = new Order();
		order.setOrderStatus(5);
		orderDeal.setOrder(order);
		List<OrderDeal> list = new ArrayList<>();

		if (ShiroUtils.hasRole(treasurer) || ShiroUtils.hasRole(admin) || ShiroUtils.hasRole(customerService)) {
			list = orderDealService.OrderDealList(orderDeal);
			return getDataTable(list);
		}

		if (ShiroUtils.hasRole(salesman)) {
			order.setSalesUserId(ShiroUtils.getUserId().intValue());
			list = orderDealService.OrderDealList(orderDeal);
			return getDataTable(list);
		}

		return getDataTable(list);
	}

	/**
	 * 新增订单
	 */
	@Log(title = "订单管理", action = "成单列表-新增订单详情页")
	@GetMapping("/add")
	@RequiresPermissions("module:order:add")
	public String add(DictData dictData, CustomerInfo customerInfo, User user, Order order, Model model) {
		// orderStatus = 5 ：成单状态的订单
		order.setOrderStatus(5);
		// 财务审核通过的单子
		order.setAuditStatus(2);
		// 查询订单类型
		List<DictData> orderList = dictDataService.selectDictDataByDictType(productType);
		model.addAttribute("orderList", orderList);
		// 生成短口令
		String token = RandomUtils.generateShortToken();
		model.addAttribute("token", token);
		return prefix + "/add";
	}

	/**
	 * 修改订单
	 */
	@Log(title = "订单管理", action = "成单列表-修改订单-查询成单详情")
	@GetMapping("/edit/{orderId}")
	@RequiresPermissions("module:order:edit")
	public String edit(@PathVariable("orderId") Integer orderId, Model model) {
		OrderDeal orderDeal = orderDealService.selectOrderDealById(orderId);
		// 获取成单中的图片
		String dealImages = orderDeal.getContractCertificate();
		List<String> dealImagesList = new ArrayList<String>();
		if (StringUtils.isNotEmpty(dealImages)) {

			String[] images = dealImages.split(",");
			for (int i = 0; i < images.length; i++) {
				dealImagesList.add("/" + images[i]);
			}
		}
		model.addAttribute("dealImagesList", dealImagesList);
		model.addAttribute("orderDeal", orderDeal);
		// 生成短口令
		String token = RandomUtils.generateShortToken();
		model.addAttribute("token", token);
		return prefix + "/edit";
	}

	/**
	 * 保存订单
	 */
	@Log(title = "订单管理", action = "成单列表-保存订单")
	@ResponseBody
	@PostMapping("/save")
	@RequiresPermissions("module:order:add")
	public Message save(Order order) {
		if (orderService.saveOrder(order) > 0) {
			return Message.ok();
		}
		return Message.error();
	}

	/**
	 * 根据用户名，手机号码，身份证查询客户信息
	 */
	@Log(title = "订单管理", action = "成单列表-新增信息-通过用户名，手机号码，身份证查询客户信息")
	@GetMapping("/customerList")
	@ResponseBody
	public String customerList(CustomerInfo customerInfo) {
		List<CustomerInfo> customerInfoList = customerInfoService.selectCustomerInfo(customerInfo);
		String jsonString = JSON.toJSONString(customerInfoList);
		return jsonString;
	}

	/**
	 * 部门派单
	 */
	@Log(title = "订单管理", action = "部门派单管理")
	@GetMapping("/dispatchDept")
	@RequiresPermissions("module:order:dispatchDeptView")
	public String dispatchDept() {
		return prefix + "/dispatchDept";
	}

	/**
	 * 部门派单列表
	 */
	@Log(title = "订单管理", action = "订单管理-部门派单列表")
	@GetMapping("/dispatchDeptList")
	@RequiresPermissions("module:order:dispatchDeptList")
	@ResponseBody
	public TableDataInfo dispatchDeptList(Order order) {
		setPageInfo(order);
		List<Order> list = null;
		if (ShiroUtils.hasRole(customerService)) {
			order.setOrderStatus(0);
			list = orderService.selectOrderList(order);
			return getDataTable(list);
		} else {
			return getDataTable(list);
		}

	}

	/**
	 * 部门派单详情
	 */
	@Log(title = "订单管理", action = "订单管理-部门派单详情页")
	@GetMapping("/dispatchDeptDetails/{orderId}")
	@RequiresPermissions("module:order:dispatchDeptDetails")
	public String dispatchDeptDetails(@PathVariable("orderId") Integer orderId, Model model) {
		// 订单查询
		Order order = orderService.selectOrderById(orderId);
		model.addAttribute("order", order);

		// 客户线索查询、
		CustomerClue customerClue = customerClueService.selectCustomerClueById(order.getClueId());
		model.addAttribute("customerClue", customerClue);

		// 参课记录
		List<CustomerAttendance> customerAttendance = customerAttendanceService
				.selectCustomerAttendanceByCellphone(customerClue.getCustomerCellphone());
		model.addAttribute("customerAttendanceList", customerAttendance);

		// 派单部门
		List<Dept> dept = deptService.selectDeptByParentId(215);
		model.addAttribute("dept", dept);

		// 派单记录
		List<OrderDispatch> dispatch = orderDispatchDao.selectOrderDispatchByOrderId(orderId);
		model.addAttribute("dispatch", dispatch);

		return prefix + "/dispatchDeptDetails";
	}

	/**
	 * 部门派单详情提交
	 */
	@Log(title = "订单管理", action = "订单管理-部门派单提交")
	@PostMapping("/detailsSave")
	@ResponseBody
	public Message detailsSave(OrderDispatch orderDispatch) {
		// 订单表状态修改
		Order order = new Order();
		order.setOrderStatus(1);
		order.setOrderId(orderDispatch.getOrderId());
		order.setDeptId(orderDispatch.getDeptId());
		order.setDeptName(orderDispatch.getDeptName());

		// 新增派单记录
		orderDispatch.setCreateBy(ShiroUtils.getLoginName());
		orderDispatch.setDispatchStatus(0);

		// 新增订单操作记录
		OrderModifyRecord orderModifyRecord = new OrderModifyRecord();
		orderModifyRecord.setOrderId(orderDispatch.getOrderId());
		orderModifyRecord.setModifyUserId(ShiroUtils.getUserId().intValue());
		orderModifyRecord.setModifyType(3);
		orderModifyRecord.setModifyRecod("部门派单");

		if (orderService.updateOrder(order) > 0 && orderDispatchService.saveOrderDispatch(orderDispatch) > 0
				&& orderModifyRecordService.saveOrderModifyRecord(orderModifyRecord) > 0) {
			return Message.ok();
		}
		return Message.error();
	}

	/**
	 * 部门派单订单流单
	 */
	@Log(title = "订单管理", action = "订单管理-流单")
	@PostMapping("/flowSheet")
	@ResponseBody
	public Message flowSheet(Order order) {
		order.setOrderStatus(7);
		order.setFinalTime(DateUtils.dateTimeStr());
		order.setOrderId(order.getOrderId());
		if (orderService.updateOrder(order) > 0) {
			orderModifyRecordService.saveOrderModifyRecord(
					new OrderModifyRecord(order.getOrderId(), ShiroUtils.getUserId().intValue(), 3, "订单流单"));
			return Message.ok();
		}
		return Message.error();
	}

	/**
	 * 业务员派单
	 */
	@Log(title = "订单管理", action = "业务员派单管理")
	@GetMapping("/dispatchSalesman")
	@RequiresPermissions("module:order:dispatchSalesmanView")
	public String dispatchSalesman() {
		return prefix + "/dispatchSalesman";
	}

	/**
	 * 业务员派单列表
	 */
	@Log(title = "订单管理", action = "订单管理-部门派单列表")
	@GetMapping("/dispatchSalesmanList")
	@RequiresPermissions("module:order:dispatchSalesmanList")
	@ResponseBody
	public TableDataInfo dispatchSalesmanList(Order order) {
		setPageInfo(order);
		List<Order> list = null;
		order.setOrderStatus(1);
		if (ShiroUtils.hasRole(dispatcherManager)) {
			list = orderService.selectOrderList(order);
			return getDataTable(list);
		} else if (ShiroUtils.hasRole(dispatcher)) {
			order.setDeptId(ShiroUtils.getUser().getDeptId().intValue());
			list = orderService.selectOrderList(order);
			return getDataTable(list);
		}
		return getDataTable(list);

	}

	/**
	 * 业务员派单详情
	 */
	@Log(title = "订单管理", action = "订单管理-业务员派单详情页")
	@GetMapping("/dispatchSalesmanDetails/{orderId}")
	@RequiresPermissions("module:order:dispatchSalesmanDetails")
	public String dispatchSalesmanDetails(@PathVariable("orderId") Integer orderId, Model model) {
		// 订单查询
		Order order = orderService.selectOrderById(orderId);
		model.addAttribute("order", order);

		// 客户线索查询
		CustomerClue customerClue = customerClueService.selectCustomerClueById(order.getClueId());
		model.addAttribute("customerClue", customerClue);

		// 客服信息
		User user = userService.selectUserById(customerClue.getCluePrincipal().longValue());
		model.addAttribute("user", user);

		// 客服建议
		CustomerClueCommunication communication = customerClueCommunicationService
				.selectCustomerClueCommunicationByClueId(order.getClueId());
		model.addAttribute("communication", communication);

		// 派单业务员
		List<User> ur = userService.selectUserByOrder(order.getOrderId(), order.getDeptId(), salesman);
		model.addAttribute("ur", ur);

		return prefix + "/dispatchSalesmanDetails";
	}

	/**
	 * 业务员派单详情提交
	 * 
	 * @throws ParseException
	 */
	@Log(title = "订单管理", action = "订单管理-部门派单提交")
	@PostMapping("/salesmanDetailsSave")
	@ResponseBody
	public Message salesmanDetailsSave(Order order) throws ParseException {
		// 订单表状态修改
		User user = userService.selectUserById(order.getSalesUserId().longValue());
		order.setSalesUserName(user.getLoginName());
		order.setOrderStatus(2);
		Order or = orderService.selectOrderById(order.getOrderId());

		// 修改派单记录
		OrderDispatch orderDispatch = new OrderDispatch();
		orderDispatch.setOrderId(order.getOrderId());
		orderDispatch.setDispatchStatus(0);
		OrderDispatch dispatch = orderDispatchService.selectOrderDispatchByDispatch(orderDispatch);
		orderDispatch.setDispatchId(dispatch.getDispatchId());// 设置派单id
		orderDispatch.setDispatchStatus(1);// 设置派单状态
		orderDispatch.setSalesUserId(order.getSalesUserId());// 设置业务员ID
		CustomerAttendance customerAttendance = new CustomerAttendance();
		// 客户线索查询
		CustomerClue customerClue = customerClueService.selectCustomerClueById(or.getClueId());
		customerAttendance.setCellphoneNum(customerClue.getCustomerCellphone());
		customerAttendance.setSalesUserId(order.getSalesUserId());
		CustomerAttendance dance = customerAttendanceService.selectCustomerAttendanceNewest(customerAttendance);
		String currentDate = DateUtils.plusDay(30, DateUtils.getDate());// 当前时间+30天
		// 判断有没有参课记录
		if (null == dance) {
			orderDispatch.setProtectType(0);// 设置为参课保护类型
			orderDispatch.setProtectTime(currentDate);// 参课保护时间，当前时间+30天
		} else {
			String danceDate = DateUtils.plusDay(30, dance.getAttendanceTime());// 跟单保护时间，参课时间+30天
			// 有参课记录但是参课时间+30天小于当前时间
			if (DateUtils.compare_date(DateUtils.getDate(), danceDate)) {
				orderDispatch.setProtectType(1);// 设置为更单保护类型
				orderDispatch.setProtectTime(currentDate);// 跟单保护时间，参课时间+30天
			} else {
				orderDispatch.setProtectType(1);// 设置为更单保护类型
				orderDispatch.setProtectTime(danceDate);// 跟单保护时间，参课时间+30天
			}
		}

		// 新增订单操作记录
		OrderModifyRecord orderModifyRecord = new OrderModifyRecord();
		orderModifyRecord.setOrderId(order.getOrderId());
		orderModifyRecord.setModifyUserId(ShiroUtils.getUserId().intValue());
		orderModifyRecord.setModifyType(3);
		orderModifyRecord.setModifyRecod("业务员派单");

		if (orderService.updateOrder(order) > 0 && orderDispatchService.updateOrderDispatch(orderDispatch) > 0
				&& orderModifyRecordService.saveOrderModifyRecord(orderModifyRecord) > 0) {
			return Message.ok();
		}
		return Message.error();
	}

	/**
	 * 业务员信息
	 */
	@Log(title = "订单管理", action = "待审核订单管理")
	@GetMapping("/follow")
	@RequiresPermissions("module:order:followView")
	String follow() {
		return prefix + "/orderFollow";
	}

	/**
	 * 查询待跟进订单列表
	 */
	@Log(title = "订单管理", action = "待跟进订单管理-查询待跟进订单")
	@GetMapping("/followList")
	@RequiresPermissions("module:order:followList")
	@ResponseBody
	public TableDataInfo orderFollowlist(Order order) {
		setPageInfo(order);
		// OrderStatus=2 ：业务员待跟进
		order.setOrderStatus(2);
		order.setSalesUserId(ShiroUtils.getUserId().intValue());
		List<Order> list = orderService.selectOrderList(order);
		return getDataTable(list);
	}

	@GetMapping("/orderVisitRecord")
	@RequiresPermissions("module:order:visitRecordView")
	String visitRecord() {
		return prefix + "/orderVisitRecord";
	}

	/**
	 * 修改线索信息
	 */
	@Log(title = "订单管理", action = "待跟进订单管理-修改线索信息")
	@GetMapping("/editFollow/{orderId}")
	@RequiresPermissions("module:order:followEdit")
	public String editFollow(@PathVariable("orderId") Integer orderId, Model model) {
		Order order = orderService.selectOrderById(orderId);
		model.addAttribute("order", order);

		// 客户线索查询、
		CustomerClue customerClue = customerClueService.selectCustomerClueById(order.getClueId());
		model.addAttribute("customerClue", customerClue);

		// 产品类型
		List<DictData> productTypeList = dictDataService.selectDictDataByDictType(productType);
		model.addAttribute("productTypeList", productTypeList);

		// 客户背景
		List<DictData> backgroundList = dictDataService.selectDictDataByDictType(customerBackground);
		model.addAttribute("backgroundList", backgroundList);

		// 客户工作
		List<DictData> jobList = dictDataService.selectDictDataByDictType(job);
		model.addAttribute("jobList", jobList);
		return prefix + "/editFollow";
	}

	/**
	 * 发起结单
	 */
	@Log(title = "订单管理", action = "结单提交")
	@GetMapping("/initiatingOrder/{orderId}")
	public String initiatingOrder(@PathVariable("orderId") Integer orderId, Model model) {
		Order order = orderService.selectOrderById(orderId);
		model.addAttribute("order", order);

		// 产品类型
		List<DictData> productTypeList = dictDataService.selectDictDataByDictType(productType);
		model.addAttribute("productTypeList", productTypeList);

		return prefix + "/initiatingOrder";
	}

	/**
	 * 保存客户线索信息
	 */
	@Log(title = "订单管理", action = "待跟进订单管理-保存客户线索信息")
	@ResponseBody
	@PostMapping("/savecustomerClue")
	public Message savecustomerClue(CustomerClue customerClue) {
		if (customerClueService.updateCustomerClue(customerClue) > 0) {
			return Message.ok();
		}
		return Message.error();
	}

	/**
	 * 查询拜访记录列表
	 */
	@Log(title = "订单管理", action = "待跟进订单管理-查询拜访记录")
	@GetMapping("/visitRecordList")
	@RequiresPermissions("module:order:visitRecordList")
	@ResponseBody
	public TableDataInfo visitRecordList(OrderVisitRecord orderVisitRecord) {
		setPageInfo(orderVisitRecord);
		List<OrderVisitRecord> visitRecordList = orderVisitRecordService.selectOrderVisitRecordList(orderVisitRecord);
		return getDataTable(visitRecordList);
	}

	/**
	 * 客户线索详情页面
	 * 
	 * @throws ParseException
	 */
	@Log(title = "订单管理", action = "待跟进订单管理-客户线索详情")
	@GetMapping("/detailsFollow/{orderId}")
	public String details(@PathVariable("orderId") Integer orderId, Model model) throws ParseException {
		List<DictData> visitList = dictDataService.selectDictDataByDictType(visitType);
		model.addAttribute("visitList", visitList);

		List<OrderVisitRecord> orderVisitRecords = orderVisitRecordService.selectOrderVisitRecordByOrderId(orderId);
		model.addAttribute("orderVisitRecords", orderVisitRecords);

		// 查询待跟进订单信息
		Order order = orderService.selectOrderById(orderId);
		model.addAttribute("order", order);

		// 查询客户线索信息
		CustomerClue customerClue = customerClueService.selectCustomerClueById(order.getClueId());
		model.addAttribute("customerClue", customerClue);

		// 查询剩余保有时间
		OrderDispatch orDispatch = new OrderDispatch();
		orDispatch.setSalesUserId(order.getSalesUserId());
		orDispatch.setOrderId(orderId);
		OrderDispatch orderDispatch = orderDispatchService.selectOrderDispatchByDispatch(orDispatch);
		model.addAttribute("orderDispatch", orderDispatch);
		long protectDay = DateUtils.getDaySub(DateUtils.getDate(), orderDispatch.getProtectTime());
		model.addAttribute("protectDay", protectDay);
		// 查询客服沟通记录
		CustomerClueCommunication clueCommunication = customerClueCommunicationService
				.selectCustomerClueCommunicationByClueId(order.getClueId());
		model.addAttribute("clueCommunication", clueCommunication);

		return prefix + "/detailsFollow";
	}

	@Log(title = "订单管理", action = "待跟进订单管理-客户线索详情")
	// @GetMapping("/getOrderVisitRecord")
	@RequestMapping(value = "/getOrderVisitRecord", method = RequestMethod.GET)
	@ResponseBody
	public Object getOrderVisitRecord(Integer recordId, Model model) throws ParseException {

		OrderVisitRecord vRecord = orderVisitRecordService.selectOrderVisitRecordById(recordId);
		return vRecord;
	}

	/**
	 * 回访记录详情页面
	 */
	@Log(title = "订单管理", action = "待跟进订单管理-回访记录详情")
	@GetMapping("/detailsVisitRecord/{orderId}/{recordId}")
	public String detailsVisitRecord(@PathVariable("orderId") Integer orderId,
			@PathVariable("recordId") Integer recordId, Model model) {
		// 查询回访列表信息
		List<OrderVisitRecord> orderVisitRecordList = orderVisitRecordService.selectOrderVisitRecordByOrderId(orderId);
		model.addAttribute("orderVisitRecordList", orderVisitRecordList);

		OrderVisitRecord orderVisitRecord = orderVisitRecordService.selectOrderVisitRecordById(recordId);
		model.addAttribute("orderVisitRecord", orderVisitRecord);
		/*
		 * Order order = orderService.selectOrderById(orderId);
		 * model.addAttribute("order", order);
		 */
		return prefix + "/detailsVisitRecord";
	}

	/**
	 * 提交回访记录信息
	 */
	@Log(title = "订单管理", action = "待跟进订单管理-回访记录提交")
	@ResponseBody
	@PostMapping("/saveVisitRecord")
	public Message saveVisitRecord(OrderVisitRecord orderVisitRecord) {
		orderVisitRecord.setVisitStatus(1);
		if (orderVisitRecordService.saveOrderVisitRecord(orderVisitRecord) > 0) {
			return Message.ok();
		}
		return Message.error();
	}

	/**
	 * 新增待跟进订单
	 */
	@Log(title = "订单管理", action = "待跟进订单管理-新增待跟进")
	@PostMapping("/followAdd")
	@RequiresPermissions("module:order:followAdd")
	public String addFollow(OrderVisitRecord orderVisitRecord, Model model) {

		List<DictData> visitList = dictDataService.selectDictDataByDictType(visitType);
		model.addAttribute("visitList", visitList);
		// OrderVisitRecord orderVisitRecord =
		// OrderVisitRecordService.selectOrderVisitRecordById(recordId);

		// 查询待跟进订单信息
		Order order = orderService.selectOrderById(orderVisitRecord.getOrderId());
		model.addAttribute("order", order);

		// 查询客户线索信息
		CustomerClue customerClue = customerClueService.selectCustomerClueById(order.getClueId());
		model.addAttribute("customerClue", customerClue);

		// 查询客服沟通记录
		CustomerClueCommunication clueCommunication = customerClueCommunicationService
				.selectCustomerClueCommunicationByClueId(order.getClueId());
		model.addAttribute("clueCommunication", clueCommunication);

		if (orderVisitRecord.getStatus() == null) {
			orderVisitRecord.setVisitStatus(0);
			orderVisitRecord.setCreateBy(ShiroUtils.getLoginName());
			orderVisitRecord.setRecordId(null);
			orderVisitRecordService.saveOrderVisitRecord(orderVisitRecord);
		}
		return prefix + "/addFollow";
	}

	/**
	 * 发起结单
	 */
	@Log(title = "订单管理", action = "发起结单")
	@ResponseBody
	@PostMapping("/initiatingOrder")
	public Message saveInitiatingOrder(Order order) {
		if (order.getProductId() != null && order.getTypeId() != null) {
			try {
				// 结单时开启成单审批工作流
				String businessId = UUID.randomUUID().toString();
				// flowId 1:成单审批 2：退单审批
				WorkFlowApply workFlowApply = new WorkFlowApply(ShiroUtils.getUserId().intValue(), businessId, 1,
						"成单审批", order.getOrderId());

				if (workFlowApplyService.saveWorkFlowApply(workFlowApply) > 0) {
					// 只有在新增情况下才能开启流程
					if (StringUtils.isNull(workFlowApply.getApplyId())) {
						// 开启成单审批流程
						commonService.startProcess(businessId, workFlowApply);

						// 修改订单状态
						Order orderInfo = new Order(order.getOrderId(), 3, 1, 1);
						orderService.updateOrder(orderInfo);
						orderService.updateOrder(order);

						// 新增订单修改记录
						OrderModifyRecord orderModifyRecord = new OrderModifyRecord(order.getOrderId(),
								ShiroUtils.getUserId().intValue(), 3, "发起结单");
						orderModifyRecordService.insertOrderModifyRecord(orderModifyRecord);

						return Message.ok();
					}

				}

			} catch (Exception e) {
				return Message.error();
			}
		}
		return Message.error();
	}

	/**
	 * 获取待审批订单：成单审核和退单审核
	 * 
	 * @return
	 */

	@GetMapping("/audit")
	@RequiresPermissions("module:order:audit")
	public String auditOrder() {
		return prefix + "/audit";
	}

	/**
	 * 获取待审批列表页面
	 * 
	 * @param order
	 * @return
	 */
	@GetMapping("/auditList")
	@RequiresPermissions("module:order:audit")
	@ResponseBody
	public Object auditOrderList(Order order, WorkFlowApply workFlowApply) throws Exception {
		setPageInfo(order);
		List<Order> auditOrderList = new ArrayList<>();

		List<Task> taskList = commonService.findTaskByUserId(String.valueOf(ShiroUtils.getUserId()));
		List<String> businessIds = new ArrayList<String>();
		String businessId = "";
		// 获取TaskIds和OrderIds
		try {
			for (Task task : taskList) {
				// 通过从任务实例中获取的流程ID，得到流程实例
				ProcessInstance result = runtimeService.createProcessInstanceQuery()
						.processInstanceId(task.getProcessInstanceId()).singleResult();
				// 入参bussinessKey
				businessId = result.getBusinessKey();
				businessIds.add(businessId);
				WorkFlowApply flowInfo = workFlowApplyService.selectWorkFlowApplyByBusinessId(businessId);
				if (flowInfo.getOrderId() != null) {
					// 将TaskId保存在Redis中:K-orderId:V-taskId
					redisServiceImpl.set(flowInfo.getOrderId().toString(), task.getId());
					redisServiceImpl.expire(flowInfo.getOrderId().toString(), 60); // 设置缓存过期时间
				}
			}

			// 无任何审批时
			if (businessIds != null && businessIds.size() > 0) {
				// 查询订单IDs
				Integer[] orderIdListIds = workFlowApplyService.selectWorkFlowApplyByBusinessIds(businessIds);
				order.setOrderIds(orderIdListIds);
				// 查询订单信息
				auditOrderList = orderService.selectOrderAuditList(order);
				if (auditOrderList != null && auditOrderList.size() > 0) {
					for (Order orderInfo : auditOrderList) {
						String orderId1 = orderInfo.getOrderId().toString();
						//
						String taskId = redisServiceImpl.get(orderId1).toString();
						// 将缓存中的taskId填充到订单数据中
						orderInfo.setTaskId(taskId);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			return Message.error(1, "数据异常请联系管理员");
		}

		return getDataTable(auditOrderList);
	}

	/**
	 * 处理待审核订单详情页面
	 * 
	 * @param orderId
	 * @param model
	 * @return
	 */
	@Log(title = "订单管理", action = "订单管理-审核订单详情")
	@GetMapping("/auditDetail/{orderId}/{taskId}")
	@RequiresPermissions("module:order:audit")
	public String processOrder(@PathVariable("orderId") Integer orderId, @PathVariable("taskId") String taskId,
			Order orders, Model model) {
		Order order = orderService.selectOrderByOrderId(orderId);
		//成单用户待审核信息
		OrderDeal orderDeal = orderDealService.selectOrderDealById(orderId);

		// 获取成单中的图片
		String dealImages = order.getOrderDeal().getContractCertificate();
		List<String> dealImagesList = new ArrayList<String>();
		if (StringUtils.isNotEmpty(dealImages)) {

			String[] images = dealImages.split(",");
			for (int i = 0; i < images.length; i++) {
				dealImagesList.add("/" + images[i]);
			}
		}
		model.addAttribute("dealImagesList", dealImagesList);

		model.addAttribute("order", order);
		model.addAttribute("orderDeal", orderDeal);
		model.addAttribute("taskId", taskId);

		// 客户职业信息
		List<DictData> jobList = dictDataService.selectDictDataByDictType(job);
		model.addAttribute("jobList", jobList);

		// 客户背景信息
		List<DictData> customerBackgroundList = dictDataService.selectDictDataByDictType(customerBackground);
		model.addAttribute("customerBackgroundList", customerBackgroundList);

		// 生成短口令
		String token = RandomUtils.generateShortToken();
		model.addAttribute("token", token);

		return prefix + "/auditDetail";
	}

	/**
	 * 财务审批订单
	 * 
	 * @param orderAudit
	 * @return
	 */
	@Log(title = "订单管理", action = "订单管理-审核订单")
	@PostMapping("/auditOrder")
	@RequiresPermissions("module:order:audit")
	public @ResponseBody Object auditOrder(OrderAudit orderAudit) {
		JSONObject object = new JSONObject();
		int ret = orderService.auditOrder(orderAudit);
		object.put("msg", ret);
		return object;
	}

	/**
	 * 财务新增成交订单
	 */
	@Log(title = "订单管理", action = "订单管理-财务成单")
	@PostMapping("/saveOrder")
	public @ResponseBody Object saveOrders(OrdersSet ordersSet) {
		ordersSet.setAuditType(1);
		JSONObject object = new JSONObject();
		// 获取创建订单信息
		int ret = orderService.foundOrder(ordersSet);
		object.put("msg", ret);
		return object;
	}

	/**
	 * 财务发起退单
	 */
	@Log(title = "订单管理", action = "订单管理-发起退单")
	@PostMapping("/refundOrders")
	public @ResponseBody Object refundOrders(OrdersSet ordersSet) {
		ordersSet.setAuditType(2);
		JSONObject object = new JSONObject();
		int ret = orderService.flowOrderDeal(ordersSet);
		object.put("msg", ret);
		return object;
	}

	/**
	 * 根据ID查询客户详情信息
	 */
	@Log(title = "订单管理", action = "成交订单-新增订单-根据ID查询客户详情信息")
	@GetMapping("/selCustomerId")
	@ResponseBody
	public String selectCustomer(CustomerInfo customerInfo) {
		customerInfoService.selectCustomerInfoById(customerInfo.getCustomerId());
		String jsonString = JSON.toJSONString(customerInfo);
		return jsonString;
	}

	/**
	 * 根据用户名和手机号查询业务员详情信息
	 */
	@Log(title = "订单管理", action = "成交订单-新增订单-根据用户名和手机号查询业务员信息")
	@GetMapping("/selUser")
	@ResponseBody
	public String userList(User user) {
		List<User> userList = userService.selectUserBySalesman(user.getPhonenumber(), salesman);
		String jsonString = JSON.toJSONString(userList);
		return jsonString;
	}

	/**
	 * 查询产品品种表
	 */
	@Log(title = "订单管理", action = "成交订单-新增订单-查询商品品种信息")
	@GetMapping("/selectList")
	@ResponseBody
	public List<ProductSpecification> selectList(ProductSpecification productSpecification) {
		List<ProductSpecification> list = productSpecificationService
				.selectProductSpecificationList(productSpecification);
		return list;
	}

	/**
	 * 查询产品类型表
	 */
	@Log(title = "订单管理", action = "成交订单-新增订单-查询商品品种信息")
	@GetMapping("/selectPriceTerm")
	@ResponseBody
	public String selectPriceTerm(ProductInfo productInfo) {
		ProductInfo productInfolist = productInfoService.selectProductInfoById(productInfo.getProductId());
		String jsonString = JSON.toJSONString(productInfolist);
		return jsonString;
	}

	/**
	 * 查询订单类型
	 */
	@Log(title = "订单管理", action = "查询订单类型")
	@GetMapping("/selectProductList")
	@ResponseBody
	public List<ProductInfo> selectProductList(ProductInfo productInfo) {
		List<ProductInfo> productLists = productInfoService.selectProductInfoList(productInfo);
		return productLists;
	}

	@Log(title = "订单管理", action = "流单列表管理")
	@GetMapping("/flow")
	@RequiresPermissions("module:order:flowview")
	String flowOrder() {
		return prefix + "/flowOrder";
	}

	/**
	 * 查询流单列表
	 */
	@Log(title = "订单管理", action = "流单列表信息")
	@GetMapping("/flowList")
	@RequiresPermissions("module:order:flowList")
	@ResponseBody
	public TableDataInfo flowList(Order order) {
		setPageInfo(order);
		order.setOrderStatus(7);
		List<Order> list = new ArrayList<>();
		if (ShiroUtils.hasRole(treasurer) || ShiroUtils.hasRole(admin) || ShiroUtils.hasRole(customerService)) {
			list = orderService.selectOrderList(order);
			return getDataTable(list);
		}
		return getDataTable(list);
	}

	/**
	 * 查看流单详情
	 */
	@Log(title = "订单管理", action = "流单列表-流单详情信息")
	@GetMapping("/orderDetail/{orderId}")
	@RequiresPermissions("module:order:orderDetail")
	public String orderDetail(@PathVariable("orderId") Integer orderId, Order orders, CustomerClue customerClue,
			Model model) {
		Order order = orderService.selectOrderById(orderId);
		model.addAttribute("order", order);
		OrderDispatch orderDispatch = orderDispatchService.selectOrderDispatchById(orderId);
		model.addAttribute("orderDispatch", orderDispatch);
		CustomerClueCommunication customerClueCommunication = customerClueCommunicationService
				.selectCustomerClueCommunicationByClueId(order.getClueId());
		model.addAttribute("customerClueCommunication", customerClueCommunication);
		customerClue.setCustomerCellphone(order.getCustomerClue().getCustomerCellphone());
		orders.setCustomerClue(customerClue);
		List<Order> ordersList = orderService.selectOrderByPhone(orders);
		model.addAttribute("ordersList", ordersList);
		return prefix + "/orderDetail";
	}
}
